package com.ikas.autumn.iec104.module.iec.utils;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.Formatter;

/**
 * 对支付串的处理工具
 *
 * @author 修唯xiuwei
 * @version 3.0
 */
@Slf4j
public class DataConvertor {
	private DataConvertor() {
	}
	/**
	 * 字节数字转16进制字符串
	 *
	 * @param ba ba
	 * @return string
	 */
	public static String byte2String(byte[] ba) {
		if (ba == null || ba.length == 0) {
			return null;
		}
		try(Formatter f = new Formatter()) {
			for (byte b : ba) {
				f.format("%02x ", b);
			}
			return f.toString();
		} catch (Exception e) {
			log.error(e.getMessage());
		}
		return null;
	}


	/**
	 * Byte append string
	 *
	 * @param bytes bytes
	 * @return the string
	 */
	public static String byteAppend(byte[] bytes) {
		StringBuilder str = new StringBuilder();
		for (int i = bytes.length - 1; i >= 0; i--) {
			str.append(String.format("%02d", bytes[i]));
		}
		return str.toString();
	}

	/**
	 * 字节数缓冲区字转16进制字符串
	 *
	 * @param buf buf
	 * @return string
	 */
	public static String byteBuf2String(ByteBuf buf) {
		if (!buf.isReadable()) {
			return null;
		}
		byte[] bs=ByteBufUtil.getBytes(buf);
		return byte2String(bs);
	}


	/**
	 * 字节数缓冲区字转16进制字符串 并解除指向
	 *
	 * @param buf buf
	 * @return string
	 */
	public static String byteBuf2StringAndRelease(ByteBuf buf) {
		String s = byteBuf2String(buf);
		ReferenceCountUtil.release(buf);
		return s;

	}

}
